package com.wang.bootbuilder.security;

import com.wang.bootbuilder.execption.CaptchaException;
import com.wang.bootbuilder.tools.Const;
import com.wang.bootbuilder.utils.RedisUtils;
import com.wang.bootbuilder.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class CaptchaFilter {

    @Autowired
    RedisUtils redisUtils;

    public void doFilterInternal(String key, String verification) throws CaptchaException {

        if (StringUtils.isNotEmpty(verification)) {
            // 校验验证码正确
            validateCaptcha(key, verification);
        }

    }

    /*
    进行校验
     */
    private void validateCaptcha(String key, String verification) throws CaptchaException {

        if (StringUtils.isEmpty(key) || StringUtils.isEmpty(verification)) {
            throw new CaptchaException(1, "验证码错误");
        }

        if (!verification.equals(redisUtils.hget(Const.CAPTCHA_KEY, key))) {
            throw new CaptchaException(1, "验证码错误");
        }

        // 销毁验证码
        redisUtils.hdel(Const.CAPTCHA_KEY, key);

    }

}
